package com.ibeeking.found.msg.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ibeeking.found.common.enums.msg.MsgTemplateTypeEnum;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.msg.rest.service.IMsgBindConfigService;
import com.ibeeking.found.msg.rest.service.IWxMpMsgTemplateService;
import com.ibeeking.found.msg.rest.service.IOpenService;
import com.ibeeking.found.msg.service.common.dos.WxMpMsgTemplateDO;
import com.ibeeking.found.msg.service.common.query.WxMpMsgTemplateQuery;
import com.ibeeking.found.msg.service.common.vo.MsgBindConfigVO;
import com.ibeeking.found.msg.service.common.vo.WxMpMsgTemplateVO;
import com.ibeeking.found.msg.service.mapper.WxMpMsgTemplateMapper;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import lombok.SneakyThrows;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @ClassName WxMpMsgTemplateServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-09-26 14:05
 **/
@Service
public class WxMpMsgTemplateServiceImpl implements IWxMpMsgTemplateService {

    @Resource
    private IOpenService wxOpenServiceImpl;

    @Resource
    private IMsgBindConfigService msgBindConfigServiceImpl;

    @Resource
    private WxMpMsgTemplateMapper wxMpMsgTemplateMapper;

    @Override
    public List<WxMpMsgTemplateVO> list(WxMpMsgTemplateQuery query) {
        List<WxMpMsgTemplateDO> templateDOS = wxMpMsgTemplateMapper.selectList(new LambdaQueryWrapper<WxMpMsgTemplateDO>()
                .eq(query.getId() != null , WxMpMsgTemplateDO::getId, query.getId())
                .eq(StringUtils.isNotEmpty(query.getTemplateId()), WxMpMsgTemplateDO::getTemplateId, query.getTemplateId())
                .eq(StringUtils.isNotEmpty(query.getTitle()), WxMpMsgTemplateDO::getTitle, query.getTitle())
        );

        List<WxMpMsgTemplateVO> templateVOS = JsonUtils.jsonToList(templateDOS, WxMpMsgTemplateVO.class);
        return templateVOS;
    }

    @Override
    public Boolean del(Long id) {
        WxMpMsgTemplateDO wxMpMsgTemplateDO = wxMpMsgTemplateMapper.selectById(id);
        if (wxMpMsgTemplateDO == null) throw new BusinessException("数据不存在");
        String templateCode = wxMpMsgTemplateDO.getTemplateId();
        if(StringUtils.isNotEmpty(templateCode)){
            List<MsgBindConfigVO> msgBindConfigVOS = msgBindConfigServiceImpl.listByTemplateType(MsgTemplateTypeEnum.MSG_TEMPLATE_WX_MP_TEXT.getCode(),templateCode);
            if(msgBindConfigVOS != null && msgBindConfigVOS.size() >0){
                throw new BusinessException("消息已经绑定，请先解绑后再删除");
            }
        }
        return wxMpMsgTemplateMapper.deleteById(id) >0;
    }

    @Override
    public String queryTemplateIdById(Long id) {
        WxMpMsgTemplateDO templateDO = wxMpMsgTemplateMapper.selectById(id);
        return null != templateDO ? templateDO.getTemplateId() : "";
    }

    @Override
    public WxMpMsgTemplateVO queryTemplateByCode(String code) {
        WxMpMsgTemplateDO templateDO = wxMpMsgTemplateMapper.selectOne(Wrappers.lambdaQuery(WxMpMsgTemplateDO.class).eq(WxMpMsgTemplateDO::getTemplateId, code));
        return JsonUtils.fromJson(templateDO, WxMpMsgTemplateVO.class);
    }

    @SneakyThrows
    @Override
    public Integer syncWxMpMsgTemplateFromWx() {
        Long tenantId = UserUtils.getTenantID();
        WxMpService wxMpService = wxOpenServiceImpl.getWxOpenMpService(tenantId);
        if (wxMpService == null) {
            throw new BusinessException("无法获取公众号信息，请检查是否绑定公众号！");
        }
        WxMpConfigStorage WxMpConfigStorage = wxMpService.getWxMpConfigStorage();
        if (WxMpConfigStorage == null) {
            throw new BusinessException("无法获取公众号信息，请检查是否绑定公众号！");
        }
        String appId = WxMpConfigStorage.getAppId();
        if(StringUtils.isEmpty(appId)){
            throw new BusinessException("无法获取公众号APPID，请检查是否绑定公众号！");
        }
        WxMpTemplateMsgService wxMpTemplateMsgService = wxMpService.getTemplateMsgService();

        if (wxMpTemplateMsgService == null) {
            throw new BusinessException("无法获取公众号信息，请检查是否绑定公众号！");
        }
        List<WxMpTemplate> templateList = wxMpTemplateMsgService.getAllPrivateTemplate();

        LogUtils.info("=====templateList:{}======", JsonUtils.toJsonStr(templateList));
        if (Collections3.isEmpty(templateList)) {
            wxMpMsgTemplateMapper.delete(null);
        } else {
            wxMpMsgTemplateMapper.delete(null);
            List<WxMpMsgTemplateDO> doos = JsonUtils.jsonToList(templateList, WxMpMsgTemplateDO.class);
            doos.stream().forEach(d->{
                d.setAppId(appId);
                d.setCreateTime(LocalDateTime.now());
                d.setModifyTime(LocalDateTime.now());
            });
            wxMpMsgTemplateMapper.insertBatchSomeColumn(doos);
        }
        return templateList.size();
    }

    @SneakyThrows
    @Override
    public List<WxMpTemplate> queryMsgTemplateListFromWx() {
        Long tenantId = UserUtils.getTenantID();
        WxMpService wxMpService = wxOpenServiceImpl.getWxOpenMpService(tenantId);
        if (wxMpService == null) {
            throw new BusinessException("无法获取公众号信息，请检查是否绑定公众号！");
        }

        WxMpTemplateMsgService wxMpTemplateMsgService = wxMpService.getTemplateMsgService();
        if (wxMpTemplateMsgService == null) {
            throw new BusinessException("无法获取公众号信息，请检查是否绑定公众号！");
        }
        List<WxMpTemplate> templateList = wxMpTemplateMsgService.getAllPrivateTemplate();
        return templateList;
    }

    private WxMpMsgTemplateServiceImpl getBean() {
        return SpringBeanUtil.getBean(WxMpMsgTemplateServiceImpl.class);
    }

}
